<template>
	<div class="sys-container">
		<el-dialog v-model="state.isShowDialog" draggable width="769px">
			<template #header>
				<div style="color: #fff">
					<el-icon size="16" style="margin-right: 3px; display: inline; vertical-align: middle"> <ele-Edit />
					</el-icon>
					<span> {{ props.title }} </span>
				</div>
			</template>
			<el-form :model="state.ruleForm" ref="ruleFormRef" size="default" label-width="80px"
				:disabled="state.isSyscontainer">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="产品名称" prop='productId'
							:rules="[{ required: true, message: '媒体产品不能为空', trigger: 'blur' }]">
							<el-select v-model.trim="state.selectedProduct" value-key="value" placeholder="请选择" class="w100"
								allow-create filterable>
								<el-option v-for='item in state.productDict' :key='item.value' :label='item.label'
									:value='item' />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label='日期'>
							<el-date-picker class='w100' v-model.trim='state.UTCDateRange' type='daterange'
								range-separator='至' start-placeholder='开始日期' end-placeholder='结束日期'
								:shortcuts='shortcuts' value-format="YYYY-MM-DD" date-format="YYYY/MM/DD"/>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="起始小时" prop="dailyStartHour">
							<el-input-number v-model.trim="state.ruleForm.dailyStartHour" placeholder="请输入起始小时" :min="0"
								:max="23" controls-position="right" class="w100"></el-input-number>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="结束小时" prop="dailyEndHour">
							<el-input-number v-model.trim="state.ruleForm.dailyEndHour" placeholder="请输入结束小时" :min="1"
								:max="23" controls-position="right" class="w100"></el-input-number>
						</el-form-item>
					</el-col>

					<el-col :xs="24" :sm="10" :md="10" :lg="10" :xl="10" class="mb20">
						<el-form-item label="到量控制" prop="arrivalType">
							<el-radio-group v-model.trim="state.ruleForm.arrivalType" @change="arrivalControl">
								<el-radio :label="1">请求</el-radio>
								<el-radio :label="2">用户</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="7" :md="7" :lg="7" :xl="7" class="mb20">
						<el-form-item label="请求上限" prop="requestLimit">
							<el-input-number v-model.trim="state.ruleForm.requestLimit" placeholder="请输入上限" :min="0"
								controls-position="right" class="w100"
								:disabled="!isArrival.isArrivalControl"></el-input-number>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="7" :md="7" :lg="7" :xl="7" class="mb20">
						<el-form-item label="用户上限" prop="userLimit">
							<el-input-number v-model.trim="state.ruleForm.userLimit" placeholder="请输入用户上限" :min="0"
								controls-position="right" class="w100"
								:disabled="isArrival.isArrivalControl"></el-input-number>
						</el-form-item>
					</el-col>

					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="互斥周期" prop="phoneUniqueMonthly">
							<el-input-number v-model.trim="state.ruleForm.phoneUniqueMonthly" placeholder="月单位" :min="0"
								controls-position="right" class="w100"></el-input-number>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="状态">
							<el-select v-model.trim="state.ruleForm.status" placeholder="请选择" class="w100">
								<el-option label="启用" :value="1"></el-option>
								<el-option label="停用" :value="2" :disabled="true"></el-option>
								<el-option label="到量" :value="3" :disabled="true"></el-option>
								<el-option label="短期关停" :value="4"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="管控级别" prop="controlLevel">
							<el-input-number v-model.trim="state.ruleForm.controlLevel" placeholder="请输入管控级别" :min="0"
								controls-position="right" class="w100"></el-input-number>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="报警用户" prop="controlLevel">
							<el-input-number v-model.trim="state.ruleForm.alarmSubscribeUser" placeholder="请输入报警订购用户" :min="0"
								controls-position="right" class="w100"></el-input-number>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="当日同步" prop="syncPlanDaily">
							<el-radio-group v-model="state.ruleForm.syncPlanDaily" class="ml-4">
								<el-radio :label="1">是</el-radio>
								<el-radio :label="2">否</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="备注">
							<el-input v-model="state.ruleForm.remark" placeholder="请输入备注内容" clearable type="textarea"
								:autosize="{ minRows: 2 }" />
						</el-form-item>
					</el-col>
					<!--  -->
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-button icon="ele-Plus" type="primary" plain @click="addExtOrgRow"> 增加省份与屏蔽城市 </el-button>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<template v-if="state.ruleForm.provinceList != undefined && state.ruleForm.provinceList.length > 0">
							<el-row :gutter="35" v-for="(v, k) in state.ruleForm.provinceList" :key="k">
								<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
									<el-form-item label="省份" :prop="`province`">
										<template #label>
											<el-button icon="ele-Delete" type="danger" circle plain size="small"
												@click="deleteExtOrgRow(k)" />
											<span class="ml5">省份</span>
										</template>
										<el-select v-model.trim="state.ruleForm.provinceList[k].province" placeholder="省份"
											class="w100" :disabled="state.isprovince" filterable>
											<el-option v-for='item in optionDict.provinceDict' :key='item.value'
												:label='item.label' :value='item.value' />
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
									<el-form-item label="屏蔽城市" prop="city">
										<el-input v-model.trim="state.ruleForm.provinceList[k].city" placeholder="请输入屏蔽城市"
											clearable></el-input>
									</el-form-item>
								</el-col>
							</el-row>
						</template>
						<el-empty :image-size="80" description="空数据" v-else></el-empty>
					</el-col>

				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="cancel" size="default">取 消</el-button>
					<el-button type="primary" @click="submit" size="default" v-show="!state.isSyscontainer">确 定</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts" setup name="editDiProductPlan">
import { reactive, ref } from 'vue';
import mittBus from '/@/utils/mitt';
import { optionDict } from '/@/const/dict';
import { convertLocalDate, datePickerShortcuts } from '/@/utils/formatTime';
import { ElLoading, ElMessage } from 'element-plus'
import { DiProductPlan } from '/@/api/models';
import SysDiCustomerProductApi from '/@/api/delivery/customerProduct';
import SysDiProductPlanApi from '/@/api/delivery/productPlan';
import { connect } from 'echarts';

const shortcuts = datePickerShortcuts();
const props = defineProps({
	title: String,
});

// 到量控制请求 & 用户 哪个可以选中并修改.
let isArrival = reactive({
	isArrivalControl: true
});

const ruleFormRef = ref();
const state = reactive({
	UTCDateRange: [new Date(), new Date()],
	selectedProduct: null,
	productDict: [],
	isShowDialog: false,
	ruleForm: {} as DiProductPlan,
	isSyscontainer: false,
	isprovince: false
});

// 打开弹窗
const openDialog = async (row: DiProductPlan, content: any) => {
	state.isSyscontainer = false;

	state.isprovince = false;

	await productDictQuery();
	state.selectedProduct = state.productDict.find((item) => {
		return item.value === row.productId;
	}) ?? null;
	state.ruleForm = row;
	state.ruleForm.syncPlanDaily = 1;
	state.ruleForm.provinceList = [{ city: row.city, province: row.province }];

	const currentDate = new Date();
    const year = currentDate.getFullYear();
    const month = String(currentDate.getMonth() + 1).padStart(2, '0');
    const day = String(currentDate.getDate()).padStart(2, '0');
	let date = `${year}-${month}-${day}`;
	let date2 = `${year + 50}-${month}-${day}`;
	state.UTCDateRange = [date,date2];
	state.isShowDialog = true;
	if (state.ruleForm.arrivalType === 1) {
		isArrival.isArrivalControl = true;
	}else{
		isArrival.isArrivalControl = false;
	}

	if (content == 'edit') {
		state.isprovince = true;
		state.UTCDateRange = [row.startTime,row.endTime];
	}
	if (content == 'details') {
		state.isSyscontainer = true;
		state.UTCDateRange = [row.startTime,row.endTime];
	}
};

// 关闭弹窗
const closeDialog = () => {
	mittBus.emit('submitRefresh');
	state.isShowDialog = false;
};

// 取消
const cancel = () => {
	state.isShowDialog = false;
};

// 提交
const submit = () => {
	const loading = ElLoading.service({
		lock: true,
		text: 'Loading',
		background: 'rgba(0, 0, 0, 0.7)',
	})
	// 类型转换成 int
	// state.ruleForm.SyncPlanDaily = state.ruleForm.SyncPlanDaily == true ? 1 :2;
	state.ruleForm.startTime = state.UTCDateRange[0];
	state.ruleForm.endTime = state.UTCDateRange[1];
	state.ruleForm.productId = state.selectedProduct?.value;
	state.ruleForm.platformId = state.selectedProduct?.exValue;
	ruleFormRef.value.validate(async (valid: boolean) => {
		if (!valid) return;
		let res;
		if (state.ruleForm.id != undefined && state.ruleForm.id > 0) {
			res = await SysDiProductPlanApi().editPost(state.ruleForm);
		} else {
			res = await SysDiProductPlanApi().addPost(state.ruleForm);
		}
		loading.close()
		if (res.data.resCode != '0000')
			ElMessage.error(res.data.resMessage);
		else {
			ElMessage.success("操作成功");
			closeDialog();
		}
	});
};

// 媒体产品列表
const productDictQuery = async () => {
	await SysDiCustomerProductApi().queryAll({ status: 1 }).then((res) => {
		if (res.data.resCode === '0000')
			state.productDict = res.data.result ?? [];
	});
};

// 增加附属机构行
const addExtOrgRow = () => {
	if (state.ruleForm.provinceList == undefined) state.ruleForm.provinceList = [];
	state.ruleForm.provinceList?.push({});
};

// 删除附属机构行
const deleteExtOrgRow = (k: number) => {
	state.ruleForm.provinceList?.splice(k, 1);
};

// 到量控制请求 & 用户 上限是否禁用
const arrivalControl = () => {
	isArrival.isArrivalControl = !isArrival.isArrivalControl;
}

// 导出对象
defineExpose({ openDialog });
</script>
